import React, { useState } from "react";
import QuestionCard from "../../components/QuestionCard";

const List = () => {
  const [questionList, setList] = useState([
    { id: "q1", title: "aa", isPublish: true },
    { id: "q2", title: "ab", isPublish: false },
    { id: "q3", title: "ac", isPublish: true },
    { id: "q4", title: "ad", isPublish: false },
  ]);

  function add() {
    let r = Math.random().toString().slice(-3);
    setList(
      questionList.concat({
        id: "q" + r,
        title: "问卷" + r,
        isPublish: Number(r) > 500 ? true : false,
      }),
    );
  }

  function del(id:string){
    setList(questionList.filter(itm => {
        if(itm.id === id) return false
        return true
    }))
  }

  function publish(id: string){
    setList(questionList.map(itm => {
        if(itm.id === id) return {...itm , isPublish : !itm.isPublish}
        return itm
    }))
  }


  return (
    <>
      <h2>问卷列表</h2>
      {questionList?.map((itm) => {
        const { id, title, isPublish } = itm;
        return (
          <QuestionCard
            key={id}
            id={id}
            title={title}
            isPublish={isPublish}
            del={del}
            publish={publish}
          />
        );
      })}
      &nbsp;
      <button onClick={add}>添加问卷</button>
    </>
  );
};

export default List;
